package com.flower.oss;

import java.util.*;

/**
 * @author lavender
 * @version 1.0
 * @date 2024-10-22 22:06
 */
public class TopTenDomains {
    public static List<String> findTopTenDomains(List<String> domainList) {
        // 使用 HashMap 来存储域名和出现的次数
        Map<String, Integer> domainCountMap = new HashMap<>();
        for (String domain : domainList) {
            domainCountMap.put(domain, domainCountMap.getOrDefault(domain, 0) + 1);
        }

        // 将域名和出现次数的映射转换为一个包含域名和次数的对象列表
        List<DomainCount> domainCountList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : domainCountMap.entrySet()) {
            domainCountList.add(new DomainCount(entry.getKey(), entry.getValue()));
        }

        // 根据出现次数对域名进行排序
        Collections.sort(domainCountList, new Comparator<DomainCount>() {
            @Override
            public int compare(DomainCount o1, DomainCount o2) {
                return o2.count - o1.count;
            }
        });

        // 取前十个域名
        List<String> topTenDomains = new ArrayList<>();
        int limit = Math.min(10, domainCountList.size());
        for (int i = 0; i < limit; i++) {
            topTenDomains.add(domainCountList.get(i).domain);
        }

        return topTenDomains;
    }

    static class DomainCount {
        String domain;
        int count;

        public DomainCount(String domain, int count) {
            this.domain = domain;
            this.count = count;
        }
    }
}